
import pymysql
class MYSQL:
    def __init__(self,host,port,user,password,database,log):
        self.__server=host
        self.__port=int(port)
        self.__user=user
        self.__password=password
        self.__database=database
        self.__log=log
        self.conn=None
        self.open()

    def open(self):
        try:
            self.close()
            self.conn=pymysql.connect(charset='utf8mb4',host=self.__server, port=self.__port, user=self.__user, password=self.__password, db=self.__database,cursorclass=pymysql.cursors.DictCursor)
            self.__log.log("数据连接成功")
        except Exception as e:
            self.__log.error(str(e),"连接错误")
    def close(self):
        try:
            self.conn.close()
        except Exception as e:
            pass

    def insert(self,str_sql,args=None):
        lastrowid=None
        commit=self.commit(str_sql,args)
        if(commit["cursor"]!=None):
            lastrowid=commit["cursor"].lastrowid
            commit["cursor"].close()
        return lastrowid

    def update(self,str_sql,args=None):
        influence_num=None
        commit=self.commit(str_sql,args)
        if(commit["cursor"]!=None):
            influence_num=commit["influence_num"]
            commit["cursor"].close()
        return influence_num

    def select(self,str_sql,args=None):
        row=None
        commit=self.commit(str_sql,args)
        if(commit["cursor"]!=None):
            row=commit["cursor"].fetchall()
            commit["cursor"].close()
        return row

    def commit(self,str_sql,args=None):
        cursor=None
        influence_num=None
        for _ in range(3):
            try:
                with self.conn.cursor() as cursor:
                    if(args==None):
                        influence_num=cursor.execute(str_sql)
                    else:
                        influence_num=cursor.execute(str_sql,args)
                    self.conn.commit()
                    break
            except Exception as e:
                self.__log.error(str(e)+" "+str_sql,"执行语句错误")
                cursor=None
                influence_num=None
                self.open()
        return {"cursor":cursor,"influence_num":influence_num}